package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class FreezeEDT extends JFrame implements ActionListener {
	
	private JButton freezer;
	private final Color defaultColor = new JButton().getBackground();
	
	public FreezeEDT() {
		super("Freeze");
		freezer = new JButton("Freeze");
		freezer.addActionListener(this);
		add(freezer, BorderLayout.WEST);
		
		JButton bLabel = new JButton("Label");
		bLabel.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				JFrame frame = new JFrame("Labels");
				final JPanel panel = new JPanel();				
				panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
				
				new Thread(new Runnable() {
						
					@Override
					public void run() {
						
								int i;
								for (i = 0; i < 5000; i++) {
									final int j = i;
									SwingUtilities.invokeLater(new Runnable() {
										
										@Override
										public void run() {
											panel.add(new JLabel("label : " + j));											
										}
									});
								}								
					}
					
				}).start();
				
				panel.setPreferredSize(new Dimension(400, 200));
				frame.add(panel);
				frame.pack();
				frame.setLocationRelativeTo(null);
				frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
				frame.setVisible(true);
			}
		});
		
		add(bLabel, BorderLayout.EAST);
		
		pack();
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
	}

	public void actionPerformed(ActionEvent e) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					SwingUtilities.invokeLater(new Runnable() {
						
						@Override
						public void run() {
							freezer.setBackground(Color.RED);		
						}
					});

					Thread.sleep(4000);
					SwingUtilities.invokeLater(new Runnable() {
						
						@Override
						public void run() {							
							freezer.setBackground(defaultColor);
						}
					});
					
					System.out.println("Finished");
				} catch (InterruptedException ei) {
				}
			}
		}).start();
	}

	public static void main(String... args) {
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				FreezeEDT edt = new FreezeEDT();
				edt.setVisible(true);
			}
		});
		
		String urlA = "http://gfx.developpez.com/tutoriel/java/swing/swing-threading/";
		String urlB = "http://hugo.developpez.com/tutoriels/java/common-problems-swing/";
		System.out.println(urlA);
		System.out.println(urlB);
	}
}